package com.limanyik.family.security.config;

import com.limanyik.family.common.entity.BasisUser;
import com.limanyik.family.security.service.BasisUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class AuthorizingConfig extends AuthorizingRealm {

    @Autowired
    BasisUserService basisUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println(principalCollection.getPrimaryPrincipal());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("sysAdmin");
        simpleAuthorizationInfo.addStringPermission("/index");
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = authenticationToken.getPrincipal().toString();
        BasisUser basisUser = basisUserService.findByAccountNumber(username);
        SimpleAuthenticationInfo simpleAuthenticationInfo = basisUser == null ? new SimpleAuthenticationInfo() : new SimpleAuthenticationInfo(basisUser, basisUser.getYourCurrentPassword(), ByteSource.Util.bytes(username), getName());
        return simpleAuthenticationInfo;
    }
}
